<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"blog.zeroable.cn","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="微信公众号：码农小谭，一个热爱coding、生活、分享、探讨的打工人，如果我的文章对你有帮助，麻烦给个关注吧~公众号分享技术博文、生活百事、欢迎关注~资料获取方式，无任何套路，也不需要解压验证码，如下：需要java相关资料请回复【java】需要数据库相关资料请回复【数据库】需要计算机网络相关资料请回复【计算机网络】需要操作系统相关资料请回复【操作系统】需要算法相关资料请回复【算法】如果资料链接失">
<meta property="og:type" content="article">
<meta property="og:title" content="netty源码解析03-pipeline详解">
<meta property="og:url" content="https://blog.zeroable.cn/2021/11/18/netty%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%9003-pipeline%E8%AF%A6%E8%A7%A3/index.html">
<meta property="og:site_name" content="zeroable">
<meta property="og:description" content="微信公众号：码农小谭，一个热爱coding、生活、分享、探讨的打工人，如果我的文章对你有帮助，麻烦给个关注吧~公众号分享技术博文、生活百事、欢迎关注~资料获取方式，无任何套路，也不需要解压验证码，如下：需要java相关资料请回复【java】需要数据库相关资料请回复【数据库】需要计算机网络相关资料请回复【计算机网络】需要操作系统相关资料请回复【操作系统】需要算法相关资料请回复【算法】如果资料链接失">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/zeroable/ima/raw/master/img/EWM_GZH_MNXT.png">
<meta property="og:image" content="https://gitee.com/zeroable/ima/raw/master/img/image-20211112104435984.png">
<meta property="og:image" content="https://gitee.com/zeroable/ima/raw/master/img/image-20211112110724253.png">
<meta property="og:image" content="https://gitee.com/zeroable/ima/raw/master/img/image-20211112141559714.png">
<meta property="og:image" content="https://gitee.com/zeroable/ima/raw/master/img/image-20211112142257571.png">
<meta property="og:image" content="https://gitee.com/zeroable/ima/raw/master/img/EWM_GZH_MNXT.png">
<meta property="article:published_time" content="2021-11-18T07:00:00.000Z">
<meta property="article:modified_time" content="2021-11-18T08:00:52.866Z">
<meta property="article:author" content="zeroable">
<meta property="article:tag" content="netty">
<meta property="article:tag" content="java">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/zeroable/ima/raw/master/img/EWM_GZH_MNXT.png">

<link rel="canonical" href="https://blog.zeroable.cn/2021/11/18/netty%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%9003-pipeline%E8%AF%A6%E8%A7%A3/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>netty源码解析03-pipeline详解 | zeroable</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">zeroable</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">微信公众号：码农小谭</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://blog.zeroable.cn/2021/11/18/netty%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%9003-pipeline%E8%AF%A6%E8%A7%A3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="zeroable">
      <meta itemprop="description" content="种一棵树最好的时间是十年前，其次是现在。">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="zeroable">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          netty源码解析03-pipeline详解
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-11-18 15:00:00 / 修改时间：16:00:52" itemprop="dateCreated datePublished" datetime="2021-11-18T15:00:00+08:00">2021-11-18</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index"><span itemprop="name">java</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/netty/" itemprop="url" rel="index"><span itemprop="name">netty</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <blockquote>
<p>微信公众号：码农小谭，一个热爱coding、生活、分享、探讨的打工人，如果我的文章对你有帮助，麻烦给个关注吧~<br>公众号分享技术博文、生活百事、欢迎关注~<br>资料获取方式，无任何套路，也不需要解压验证码，如下：<br>需要java相关资料请回复【java】<br>需要数据库相关资料请回复【数据库】<br>需要计算机网络相关资料请回复【计算机网络】<br>需要操作系统相关资料请回复【操作系统】<br>需要算法相关资料请回复【算法】<br>如果资料链接失效，请点击联系作者添加微信，第一时间会进行更新。</p>
</blockquote>
<p><img src="https://gitee.com/zeroable/ima/raw/master/img/EWM_GZH_MNXT.png"></p>
<blockquote>
<p>提示:如果没有听过或者使用过java nio 和netty，不建议直接阅读此文章，建议先去了解java nio 和netty之后再阅读此文章。</p>
</blockquote>
<span id="more"></span>

<h1 id="pipeline详解"><a href="#pipeline详解" class="headerlink" title="pipeline详解"></a>pipeline详解</h1><h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>上一篇文章，我们知道了新连接做了哪些事情，包括从服务端重新注册<code>interestOps</code>开始真正监听新连接事件，然后到新连接的处理，包括从新连接的初步注册，再到新连接重新注册<code>interestOps</code>。基本上</p>
<p>我们之前的俩篇文章都是在介绍netty的东西，比较少的接触到JDK 底层的NIO 代码。通过这篇文章，我们就能就知道，netty是怎么获取新连接的，以及对新连接的处理。</p>
<h2 id="服务端流程的回顾"><a href="#服务端流程的回顾" class="headerlink" title="服务端流程的回顾"></a>服务端流程的回顾</h2><p>通过前面文章的分析，我们知道，服务端NioEventLoop线程启动，发生在<code>AbstractBootstrap.doBind0();</code>方法中，通过往NioEventLoop中添加一个task任务来启动线程。但是对应的selector对任何事件都不感兴趣，也就是<code>readInterestOp</code>为0。绑定端口成功后，才通过<code>pipeline.fireChannelActive();</code>把NioServerSocketChannel上的<code>SelectionKey.OP_ACCEPT</code>也就是16 重新添加到selectionKey上。那我们来仔细分析这个怎么重新添加新的<code>SelectionKey</code>的。</p>
<h3 id="初次注册SelectionKey"><a href="#初次注册SelectionKey" class="headerlink" title="初次注册SelectionKey"></a>初次注册SelectionKey</h3><p>如果你看过之前的文章，那么这个你应该会知道，这个注册发生在netty调用JDK Nio底层的注册，并且将netty的NioServerSocketChannel当做一个att绑定到jdk 的channel上。我们再次复习一下把~</p>
<p><img src="https://gitee.com/zeroable/ima/raw/master/img/image-20211112104435984.png" alt="image-20211112104435984"></p>
<p>通过上面的流程可以发现，通过<code>selectionKey = javaChannel().register(eventLoop().selector, 0, this);</code>这里的参数0就是最开始的interestOps。</p>
<h3 id="重新绑定SelectionKey"><a href="#重新绑定SelectionKey" class="headerlink" title="重新绑定SelectionKey"></a>重新绑定SelectionKey</h3><p>然后等待到端口绑定完成后，netty会是用<code>pipeline.fireChannelActive();</code>对完成事件进行传播，如下图：</p>
<p><img src="https://gitee.com/zeroable/ima/raw/master/img/image-20211112110724253.png" alt="image-20211112110724253"></p>
<p>pipeline有head和tail节点，事件的传播都是从head节点开始传播，点进fireChannelActive中，我们可以看到：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//DefaultChannelPipeline.java</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> ChannelPipeline <span class="title">fireChannelActive</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 这里就是从head节点开始传播，我们继续查看invokeChannelActive方法</span></span><br><span class="line">    AbstractChannelHandlerContext.invokeChannelActive(head);</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> <span class="title">invokeChannelActive</span><span class="params">(<span class="keyword">final</span> AbstractChannelHandlerContext next)</span> </span>&#123;</span><br><span class="line">    EventExecutor executor = next.executor();</span><br><span class="line">    <span class="keyword">if</span> (executor.inEventLoop()) &#123;</span><br><span class="line">        <span class="comment">// 继续跟踪这个invokeChannelActive.</span></span><br><span class="line">        next.invokeChannelActive();</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        executor.execute(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                next.invokeChannelActive();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//DefaultChannelPipeline.HeadContext.java</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ctx.fireChannelActive();</span><br><span class="line"></span><br><span class="line">    readIfIsAutoRead();</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">readIfIsAutoRead</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (channel.config().isAutoRead()) &#123;</span><br><span class="line">        <span class="comment">// 这里触发了channel的read方法，我们知道，这个channel指的是NioServerSocketChannel.</span></span><br><span class="line">        <span class="comment">// 这里又调用了pipeline的read方法，不过这个read方法，是直接是用尾节点tail。</span></span><br><span class="line">        <span class="comment">// 最终还是通过unsafe的beginRead进行操作。</span></span><br><span class="line">        <span class="comment">// 这里为啥这么绕呢，看着人真头疼，其实可以类比我们平时坐的公交车，起点站到终点站的路线并不是直线，也不是最短的。</span></span><br><span class="line">        <span class="comment">// 这是因为要兼顾旁边的地区，不然会导致有的地方又公交车站，有的地方没有公交车站，虽然绕了，但是给人们出行提供了便利。</span></span><br><span class="line">        <span class="comment">// 这也就是为啥netty是用一个pipeline，还要在pipeline中添加head和tail俩个节点，这样就可以覆盖范围更大一点。</span></span><br><span class="line">        channel.read();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// AbstractChannel.AbstractUnsafe.java</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">beginRead</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    assertEventLoop();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (!isActive()) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        doBeginRead();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (<span class="keyword">final</span> Exception e) &#123;</span><br><span class="line">        invokeLater(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                pipeline.fireExceptionCaught(e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        close(voidPromise());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// AbstractNioChannel.java</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doBeginRead</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// Channel.read() or ChannelHandlerContext.read() was called</span></span><br><span class="line">    <span class="comment">// 这个selectionKey就是在NioServerSocketChannel的构造方法中，传入的一个SelectionKey.OP_ACCEPT,也就是16。</span></span><br><span class="line">    <span class="comment">// super(null, channel, SelectionKey.OP_ACCEPT);</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">final</span> SelectionKey selectionKey = <span class="keyword">this</span>.selectionKey;</span><br><span class="line">    <span class="keyword">if</span> (!selectionKey.isValid()) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    readPending = <span class="keyword">true</span>;</span><br><span class="line">	<span class="comment">//直到这里，才开始正真监听连接事件。</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> interestOps = selectionKey.interestOps();</span><br><span class="line">    <span class="keyword">if</span> ((interestOps &amp; readInterestOp) == <span class="number">0</span>) &#123;</span><br><span class="line">        selectionKey.interestOps(interestOps | readInterestOp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="新连接的处理"><a href="#新连接的处理" class="headerlink" title="新连接的处理"></a>新连接的处理</h2><p>重新绑定了事件后，才开始监听连接事件。</p>
<h3 id="新连接的检测"><a href="#新连接的检测" class="headerlink" title="新连接的检测"></a>新连接的检测</h3><p>我们知道服务端的线程在绑定端口前就启动了，这个线程就是轮询进行获取事件，其中就包括新连接事件。还记得上一篇文章分析NioEventLoop时讲到的<code>select();</code>方法吗？通过这个方法，调用JDK NIO 底层的<code>select();</code>方法，获取网络IO。然后通过<code>processSelectedKeys();</code>来处理IO事件。这里netty对原来的SelectKeySet进行了优化，然后遍历这个集合，查找对应的事件：</p>
<p><img src="https://gitee.com/zeroable/ima/raw/master/img/image-20211112141559714.png" alt="image-20211112141559714"></p>
<h3 id="新连接的处理-1"><a href="#新连接的处理-1" class="headerlink" title="新连接的处理"></a>新连接的处理</h3><p>这里触发了<code>unsafe.read();</code>事件。如下：</p>
<p><img src="https://gitee.com/zeroable/ima/raw/master/img/image-20211112142257571.png" alt="image-20211112142257571"></p>
<p>我们看看<code>doReadMessages();</code>做了些啥：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//NioServerSocketChannel.java</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">int</span> <span class="title">doReadMessages</span><span class="params">(List&lt;Object&gt; buf)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    SocketChannel ch = javaChannel().accept();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (ch != <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="comment">// 这里将新连接封装成一个NIOSocketChannel,加入buf集合中。</span></span><br><span class="line">            buf.add(<span class="keyword">new</span> NioSocketChannel(<span class="keyword">this</span>, ch));</span><br><span class="line">            <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        logger.warn(<span class="string">&quot;Failed to create a new channel from an accepted socket.&quot;</span>, t);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            ch.close();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t2) &#123;</span><br><span class="line">            logger.warn(<span class="string">&quot;Failed to close a socket.&quot;</span>, t2);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>上面的while条件中的<code>allocHandle.incMessagesRead();</code>代码如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">continueReading</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> config.isAutoRead() &amp;&amp;</span><br><span class="line">        attemptedBytesRead == lastBytesRead &amp;&amp;</span><br><span class="line">        totalMessages &lt; maxMessagePerRead &amp;&amp;</span><br><span class="line">        totalBytesRead &lt; Integer.MAX_VALUE;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们继续查看下面的代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> size = readBuf.size();</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; size; i ++) &#123;</span><br><span class="line">    readPending = <span class="keyword">false</span>;</span><br><span class="line">    <span class="comment">// 这里通过pipeline进行传播read事件，这里也就是新连接事件。</span></span><br><span class="line">    pipeline.fireChannelRead(readBuf.get(i));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="新连接的注册"><a href="#新连接的注册" class="headerlink" title="新连接的注册"></a>新连接的注册</h3><p>还记得我们在ServerBootstrap的<code>dobind()</code>方法中的<code>initAndRegister()</code>吗？里面的<code>init(channel)</code>中，我们再次复习一下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">init</span><span class="params">(Channel channel)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    <span class="comment">// 。。。 非重要代码省略。。。。</span></span><br><span class="line">    ChannelPipeline p = channel.pipeline();</span><br><span class="line">    p.addLast(<span class="keyword">new</span> ChannelInitializer&lt;Channel&gt;() &#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initChannel</span><span class="params">(Channel ch)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">            <span class="keyword">final</span> ChannelPipeline pipeline = ch.pipeline();</span><br><span class="line">            ChannelHandler handler = config.handler();</span><br><span class="line">            <span class="keyword">if</span> (handler != <span class="keyword">null</span>) &#123;</span><br><span class="line">                pipeline.addLast(handler);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="comment">// We add this handler via the EventLoop as the user may have used a ChannelInitializer as handler.</span></span><br><span class="line">            <span class="comment">// In this case the initChannel(...) method will only be called after this method returns. Because</span></span><br><span class="line">            <span class="comment">// of this we need to ensure we add our handler in a delayed fashion so all the users handler are</span></span><br><span class="line">            <span class="comment">// placed in front of the ServerBootstrapAcceptor.</span></span><br><span class="line">            </span><br><span class="line">            <span class="comment">// 我们通过EventLoop添加此处理程序，因为用户可能使用了ChannelInitializer作为处理程序。</span></span><br><span class="line">			<span class="comment">// 在这种情况下，只有在该方法返回后才会调用initChannel（…）方法。</span></span><br><span class="line">            <span class="comment">// 因此，我们需要确保以延迟方式添加处理程序，以便所有用户处理程序都放在ServerBootstrapAcceptor前面。</span></span><br><span class="line">            ch.eventLoop().execute(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                    <span class="comment">// 这里就是将一个handler添加到pipeline的tail节点之前。</span></span><br><span class="line">                    <span class="comment">// 这个ServerBootstrapAcceptor就是处理新连接事件的，我们可以点进去查看一下。</span></span><br><span class="line">                    pipeline.addLast(<span class="keyword">new</span> ServerBootstrapAcceptor(</span><br><span class="line">                        currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>从上面的就可以看出来，其实在初始化channel的时候，netty就将处理新连接事件的handler添加到pipeline中了，等到新连接接入时，就可以调用<code>pipeline.fireChannelRead();</code>从head节点依次往下进行传播，直到传播到<code>ServerBootstrapAcceptor</code>这里，我们看看这个<code>ServerBootstrapAcceptor.channelRead();</code>做了哪些事情吧：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="meta">@SuppressWarnings(&quot;unchecked&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelRead</span><span class="params">(ChannelHandlerContext ctx, Object msg)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> Channel child = (Channel) msg;</span><br><span class="line">	<span class="comment">// 将childHandler绑定到子Channel的pipeline中的节点上。</span></span><br><span class="line">    child.pipeline().addLast(childHandler);</span><br><span class="line">	<span class="comment">// 然后循环把一些客户端的属性添加到配置中。</span></span><br><span class="line">    <span class="keyword">for</span> (Entry&lt;ChannelOption&lt;?&gt;, Object&gt; e: childOptions) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (!child.config().setOption((ChannelOption&lt;Object&gt;) e.getKey(), e.getValue())) &#123;</span><br><span class="line">                logger.warn(<span class="string">&quot;Unknown channel option: &quot;</span> + e);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">            logger.warn(<span class="string">&quot;Failed to set a channel option: &quot;</span> + child, t);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">	</span><br><span class="line">    <span class="keyword">for</span> (Entry&lt;AttributeKey&lt;?&gt;, Object&gt; e: childAttrs) &#123;</span><br><span class="line">        child.attr((AttributeKey&lt;Object&gt;) e.getKey()).set(e.getValue());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 这里就调用work那个NioEventLoopGroup中选择一个NioEventLoop进行注册。</span></span><br><span class="line">        <span class="comment">// 那么这个新连接的读事件都是通过这个NioEventLoop进行操作。</span></span><br><span class="line">        <span class="comment">// 到这里就完成新连接的检测和处理。</span></span><br><span class="line">        childGroup.register(child).addListener(<span class="keyword">new</span> ChannelFutureListener() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">operationComplete</span><span class="params">(ChannelFuture future)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">                <span class="keyword">if</span> (!future.isSuccess()) &#123;</span><br><span class="line">                    forceClose(child, future.cause());</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        forceClose(child, t);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我们继续跟进<code>childGroup.register();</code> 那我们应该知道，这里的register在<code>NioEventLoopGroup</code>中，其实就是在这个group中选择选择一个<code>NioEventLoop</code>进行注册，也就是调用了<code>next().register();</code>这个我们之前都说过了，那么我们就不再重复的粘贴代码了，最终也是到了<code>channel</code>的<code>unSafe.register();</code>方法，这里的<code>channel</code> 就不是我们之前说过的<code>NIoServerSocketChannel</code>了,而是<code>NioSocketChannel</code>,所以们去这个类下的<code>unsafe</code>类，这个<code>register</code>在父类<code>AbstractUnsafe</code>中。</p>
<h3 id="新连接重新绑定SelectionKey"><a href="#新连接重新绑定SelectionKey" class="headerlink" title="新连接重新绑定SelectionKey"></a>新连接重新绑定SelectionKey</h3><p>然而在这个方法中，最终调用的是<code>doRegister();</code>也就是通过<code>selectionKey = javaChannel().register(eventLoop().selector, 0, this);</code>将新的连接的<code>JDK</code> 底层的<code>channel</code>绑定到<code>selector</code>上，并将这个<code>netty</code>的<code>NioSocketChannel</code>对象作为一个<code>attachment</code>也绑定到<code>selector</code>上。注意此时绑定的<code>interestOps</code>还是0，并未将读事件绑定到<code>selector</code>上。其实和服务端绑定端口一样，其实并不是注册的时候就把对应的事情一起注册到<code>selector</code>上，而是在完成后，在通过<code>pipeline</code>传播的方式，也就是<code>pipeline.fireChannelActive();</code>这里进行传播，我们看看调用<code>doRegister();</code>放法的<code>register0()</code>的具体实现吧：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// AbstractChannel.java</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">register0</span><span class="params">(ChannelPromise promise)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// check if the channel is still open as it could be closed in the mean time when the register</span></span><br><span class="line">        <span class="comment">// call was outside of the eventLoop</span></span><br><span class="line">        <span class="keyword">if</span> (!promise.setUncancellable() || !ensureOpen(promise)) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 首先是从来没有注册过，这里就是为true。</span></span><br><span class="line">        <span class="keyword">boolean</span> firstRegistration = neverRegistered;</span><br><span class="line">        <span class="comment">//这里进行注册。</span></span><br><span class="line">        doRegister();</span><br><span class="line">        <span class="comment">// 修改状态。</span></span><br><span class="line">        neverRegistered = <span class="keyword">false</span>;</span><br><span class="line">        registered = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Ensure we call handlerAdded(...) before we actually notify the promise. This is needed as the</span></span><br><span class="line">        <span class="comment">// user may already fire events through the pipeline in the ChannelFutureListener.</span></span><br><span class="line">        pipeline.invokeHandlerAddedIfNeeded();</span><br><span class="line"></span><br><span class="line">        safeSetSuccess(promise);</span><br><span class="line">        pipeline.fireChannelRegistered();</span><br><span class="line">        <span class="comment">// Only fire a channelActive if the channel has never been registered. This prevents firing</span></span><br><span class="line">        <span class="comment">// multiple channel actives if the channel is deregistered and re-registered.</span></span><br><span class="line">        <span class="comment">// 因为客户端连接不需要绑定端口，只需要进行注册就行，所以这里isActive()为他true。</span></span><br><span class="line">        <span class="keyword">if</span> (isActive()) &#123;</span><br><span class="line">            <span class="keyword">if</span> (firstRegistration) &#123;</span><br><span class="line">                <span class="comment">// 在这里进行传播。</span></span><br><span class="line">                pipeline.fireChannelActive();</span><br><span class="line">            &#125; <span class="keyword">else</span> <span class="keyword">if</span> (config().isAutoRead()) &#123;</span><br><span class="line">                <span class="comment">// This channel was registered before and autoRead() is set. This means we need to begin read</span></span><br><span class="line">                <span class="comment">// again so that we process inbound data.</span></span><br><span class="line">                <span class="comment">//</span></span><br><span class="line">                <span class="comment">// See https://github.com/netty/netty/issues/4805</span></span><br><span class="line">                beginRead();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Throwable t) &#123;</span><br><span class="line">        <span class="comment">// Close the channel directly to avoid FD leak.</span></span><br><span class="line">        closeForcibly();</span><br><span class="line">        closeFuture.setClosed();</span><br><span class="line">        safeSetFailure(promise, t);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><code>fireChannelActive</code>从pipeline的head开始传播，而head其实就是<code>HeadContext</code>类的一个实例，所以我们通过层层跟踪，那么也就在<code>DefaultChannelPipe</code>的内部类<code>HeadContext</code>中的<code>channelActive();</code>方法，源代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// DefaultChannelPipeline.HeadContext.java</span></span><br><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">channelActive</span><span class="params">(ChannelHandlerContext ctx)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    ctx.fireChannelActive();</span><br><span class="line"></span><br><span class="line">    readIfIsAutoRead();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>其实看到这里就已经非常明白了，和服务端启动一样，绑定端口完成后，也是通过<code>pipeline.fireChannelActive();</code>进行传播，然后调用<code>readIfIsAutoRead();</code>然后调用<code>channel.read();</code>这个又会回到<code>pipeline.read();</code>不过这里是直接就是调用尾节点<code>tail.read();</code>，<code>tail</code> 和<code>head</code>一样，都是<code>HeadContext</code>类的一个实例。所以查看<code>HeadContext.read();</code>方法，最终还是回到了<code>channel.unsafe.beginRead();</code>方法。</p>
<p>和服务端的一样，也是将<code>netty</code>的<code>channel</code>上的<code>interestOps</code>重新添加到<code>selectionKey</code>上。唯一的区别就是服务端的<code>interestOps</code>是16，而新连接的<code>interestOps</code>是1，这里可以查看一下<code>NioServerSocketChannel</code>和<code>NioSocketChannel</code>构造函数的区别，前面传入的是<code>accept</code>事件，后面传入的是<code>read</code>事件。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>到这里，一个新的连接接入的流程我们已经分析完成了，从服务端绑定了端口以后就开始正式启动新连接的检测了，因为把感兴趣的<code>accept</code>事件绑定到了服务端的<code>selectionKey</code>上，表示这个对连接事件感兴趣。</p>
<p>然后服务端轮询到新连接后，先获取这个连接的<code>channel</code>然后将这个<code>JDK</code> 底层的<code>channel</code>封装成一个<code>NioSocketChannel</code>，然后通过服务端的<code>pipeline</code>进行传播，我们之前知道，在初始化服务端<code>channel</code>是，会往服务端<code>pipeline</code>添加一个特殊的<code>handler</code>，这个特殊的<code>handler</code>就是<code>ServerBootstrapAcceptor</code>，那么会从pipeline从head传播到这个<code>chandler</code>，而这个handler做的事情，就是从<code>childGroup</code>中选择一个<code>NioEventLoop</code> 进行selector的注册。</p>
<p>注册后又通过<code>pipeline.fireChannelActive();</code>进行通知，这里主要做的事情就是重新将<code>interestOps</code>绑定到<code>selectionKey</code>上，这个时候，已经完成了新连接的接入，说明这个连接已经可以接受对应的客户端发送的数据，也就是能进行<code>read</code>事件的检测。</p>
<p>从服务端启动到现在的新连接的接入，我们能发现，这个<code>pipeline</code>无处不在，也能看出来这个<code>pipeline</code> 的重要性，我们下篇文章就来详细讲解<code>pipeline</code>，如果想详细了解的，不妨点个关注，顺便关注一下微信公众号：<strong>码农小谭</strong>，你将会在我发布的第一时间收到消息~</p>
<blockquote>
<p>微信公众号：码农小谭，一个热爱coding、生活、分享、探讨的打工人，如果我的文章对你有帮助，麻烦给个关注吧~<br>公众号分享技术博文、生活百事、欢迎关注~<br>资料获取方式，无任何套路，也不需要解压验证码，如下：<br>需要java相关资料请回复【java】<br>需要数据库相关资料请回复【数据库】<br>需要计算机网络相关资料请回复【计算机网络】<br>需要操作系统相关资料请回复【操作系统】<br>需要算法相关资料请回复【算法】<br>如果资料链接失效，请点击联系作者添加微信，第一时间会进行更新。</p>
</blockquote>
<p><img src="https://gitee.com/zeroable/ima/raw/master/img/EWM_GZH_MNXT.png"></p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/netty/" rel="tag"># netty</a>
              <a href="/tags/java/" rel="tag"># java</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/11/10/netty%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%9002-%E6%96%B0%E8%BF%9E%E6%8E%A5%E7%9A%84%E5%A4%84%E7%90%86/" rel="prev" title="netty源码解析02-新连接的处理以及添加读事件的添加">
      <i class="fa fa-chevron-left"></i> netty源码解析02-新连接的处理以及添加读事件的添加
    </a></div>
      <div class="post-nav-item"></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    
  <div class="comments">
    <div id="lv-container" data-id="city" data-uid="MTAyMC81NDY0NS8zMTExNg=="></div>
  </div>
  

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#pipeline%E8%AF%A6%E8%A7%A3"><span class="nav-number">1.</span> <span class="nav-text">pipeline详解</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%89%8D%E8%A8%80"><span class="nav-number">1.1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9C%8D%E5%8A%A1%E7%AB%AF%E6%B5%81%E7%A8%8B%E7%9A%84%E5%9B%9E%E9%A1%BE"><span class="nav-number">1.2.</span> <span class="nav-text">服务端流程的回顾</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%9D%E6%AC%A1%E6%B3%A8%E5%86%8CSelectionKey"><span class="nav-number">1.2.1.</span> <span class="nav-text">初次注册SelectionKey</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%87%8D%E6%96%B0%E7%BB%91%E5%AE%9ASelectionKey"><span class="nav-number">1.2.2.</span> <span class="nav-text">重新绑定SelectionKey</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%96%B0%E8%BF%9E%E6%8E%A5%E7%9A%84%E5%A4%84%E7%90%86"><span class="nav-number">1.3.</span> <span class="nav-text">新连接的处理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%B0%E8%BF%9E%E6%8E%A5%E7%9A%84%E6%A3%80%E6%B5%8B"><span class="nav-number">1.3.1.</span> <span class="nav-text">新连接的检测</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%B0%E8%BF%9E%E6%8E%A5%E7%9A%84%E5%A4%84%E7%90%86-1"><span class="nav-number">1.3.2.</span> <span class="nav-text">新连接的处理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%B0%E8%BF%9E%E6%8E%A5%E7%9A%84%E6%B3%A8%E5%86%8C"><span class="nav-number">1.3.3.</span> <span class="nav-text">新连接的注册</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%B0%E8%BF%9E%E6%8E%A5%E9%87%8D%E6%96%B0%E7%BB%91%E5%AE%9ASelectionKey"><span class="nav-number">1.3.4.</span> <span class="nav-text">新连接重新绑定SelectionKey</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">1.4.</span> <span class="nav-text">总结</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">zeroable</p>
  <div class="site-description" itemprop="description">种一棵树最好的时间是十年前，其次是现在。</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">4</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">2</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">2</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:2011277648@qq.com" title="E-Mail → mailto:2011277648@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/zeroable/ima/raw/master/img/EWM_GZH_MNXT.png" title="微信公众号 → https:&#x2F;&#x2F;gitee.com&#x2F;zeroable&#x2F;ima&#x2F;raw&#x2F;master&#x2F;img&#x2F;EWM_GZH_MNXT.png" rel="noopener" target="_blank"><i class="fab fa-weixin fa-fw"></i>微信公众号</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.zhihu.com/people/zeroable" title="知乎 → https:&#x2F;&#x2F;www.zhihu.com&#x2F;people&#x2F;zeroable" rel="noopener" target="_blank"><i class="fab fa-zhihu fa-fw"></i>知乎</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/qq_36707152" title="csdn → https:&#x2F;&#x2F;blog.csdn.net&#x2F;qq_36707152" rel="noopener" target="_blank"><i class="fab fa-csdn fa-fw"></i>csdn</a>
      </span>
  </div>



      </div>
      <div class="wechat_OA">
        <span>欢迎关注我的公众号</span>
        <br>
          <!-- 这里添加你的二维码图片 -->
        <img src ="https://gitee.com/zeroable/ima/raw/master/img/微信公众号.jpg">
      </div

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">zeroable</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

<script>
NexT.utils.loadComments(document.querySelector('#lv-container'), () => {
  window.livereOptions = {
    refer: location.pathname.replace(CONFIG.root, '').replace('index.html', '')
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
});
</script>

</body>
</html>
